﻿namespace CRM_Perf_BenchMark
{
	using System;
	using System.Collections.Generic;
    using Microsoft.VisualStudio.TestTools.WebTesting;
	using System.Net;
	using System.Text;
	using System.Xml;
	
    /// <summary>
    /// 1. Start at Workplace homepage
    /// 2. Click Reports
    /// 3. Double Click Campaign Activity Status
    /// 4. Click Run Report
    /// </summary>

	public class CampaignActivityStatusReport : CrmWebTest
	{
		public void CampaignActivityStatusReport_PreWebTest(object sender, PreWebTestEventArgs e)
		{
            EntityRequest er = new EntityRequest();
            er.Type = EntityNames.Users;
            er.ReturnAs = EntityNames.Users;
            er.ParentID = EntityManager.Instance.OrgId;

            System.Collections.Hashtable userProps = new System.Collections.Hashtable();
            if (e.WebTest.Context.ContainsKey("UserRole"))
            {
                userProps.Add("role", e.WebTest.Context["UserRole"]);
                er.Props = userProps;
            }
            
            System.Collections.Hashtable Entities = EntityManager.Instance.GetEntities(er);

            user = (CRMEntity)Entities[EntityNames.Users];

            crmServer = user["CrmServer"];
            tokenKey = EntityManager.Instance.ReadTokenKey(user["organizationid"]);

            e.WebTest.UserName = user["domainName"];
            e.WebTest.Password = user["userpassword"];
            
            er = new EntityRequest();
            er.Type = EntityNames.Reports;
            er.ParentID = new Guid(user["organizationid"]);
            er.ReturnAs = EntityNames.Reports;

            System.Collections.Hashtable reportProps = new System.Collections.Hashtable();
            reportProps.Add("filename", "Campaign Activity Status.rdl");
            er.Props = reportProps;

            report = (CRMEntity)(EntityManager.Instance.GetEntities(er)[EntityNames.Reports]);
            EntityManager.Instance.FreeEntity(report);            
		}
		
        public void CampaignActivityStatusReport_PostWebTest(object sender, PostWebTestEventArgs e)
		{
			EntityManager.Instance.FreeEntity(user);            
		}

		public CampaignActivityStatusReport()
		{
			WebRequest.RegisterPrefix("crm", new crmRequestFactory());

			this.Proxy = null;            
			PreWebTest += new EventHandler<PreWebTestEventArgs>(CampaignActivityStatusReport_PreWebTest);
			PostWebTest += new EventHandler<PostWebTestEventArgs>(CampaignActivityStatusReport_PostWebTest);
		}

		public override IEnumerator<WebTestRequest> GetRequestEnumerator()
		{
            this.BeginTransaction("NavReportHomepage");

            CRMReports_home_reports_aspx reports = new CRMReports_home_reports_aspx(user);
			yield return (reports);

            this.EndTransaction("NavReportHomepage");

			this.BeginTransaction("CampaignActivityStatusReport");

            crmreports_viewer_viewer_aspx viewer = new crmreports_viewer_viewer_aspx(user);
			viewer.id = new Guid(report["reportid"]);
			viewer.helpId = report["filename"];
			viewer.action = "filter";
            yield return (viewer);

            AdvancedFind.AdvancedFind af = new AdvancedFind.AdvancedFind();
            WebTestRequest wtr = null;

            try { af.GetDefaultAdvancedFindView("campaignactivity", false); }
            catch (crmException x)
            {
                wtr = (CrmRequest)x.wtr;
                wtr.Url = Utils.ReplaceServerName(wtr.Url, user);
            }
            yield return (wtr);

            wtr = null;
            try { af.GetEntityFieldList("campaignactivity"); }
            catch (crmException x)
            {
                wtr = (CrmRequest)x.wtr;
                wtr.Url = Utils.ReplaceServerName(wtr.Url, user);

                string urlPath = wtr.Url.Remove(0, crmServer.Length);
                urlPath = urlPath.Remove(0, user["organizationName"].Length + 1);

                rpcInfo = Utils.GenerateWRPCToken(urlPath, user, tokenKey);

                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctokentimestamp";
                headerItem.Value = rpcInfo.timeStamp.ToString();
                wtr.Headers.Add(headerItem);
                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctoken";
                headerItem.Value = rpcInfo.token;
                wtr.Headers.Add(headerItem);
                wtr.Method = "Post";
            }
            yield return (wtr);

            try { af.GetLinkedEntityList("campaignactivity"); }
            catch (crmException x)
            {
                wtr = (CrmRequest)x.wtr;
                wtr.Url = Utils.ReplaceServerName(wtr.Url, user);

                string urlPath = wtr.Url.Remove(0, crmServer.Length);
                urlPath = urlPath.Remove(0, user["organizationName"].Length + 1);

                rpcInfo = Utils.GenerateWRPCToken(urlPath, user, tokenKey);

                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctokentimestamp";
                headerItem.Value = rpcInfo.timeStamp.ToString();
                wtr.Headers.Add(headerItem);
                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctoken";
                headerItem.Value = rpcInfo.token;
                wtr.Headers.Add(headerItem);
                wtr.Method = "Post";
            }
            yield return (wtr);

            CRMReports_rsviewer_reportviewer_aspx rsviewer = new CRMReports_rsviewer_reportviewer_aspx(crmServer);
            rsviewer.id = new Guid(report["reportid"]);
            rsviewer.isScheduledReport = false;
            rsviewer.CRM_filter = "<ReportFilter><ReportEntity paramname=\"CRM_FilteredCampaignActivity\" displayname=\"Campaign Activities\"><fetch version=\"1.0\" output-format=\"xml-platform\" mapping=\"logical\" distinct=\"false\"><entity name=\"campaignactivity\"><all-attributes/><filter type=\"and\"><condition attribute=\"ownerid\" operator=\"eq-userid\"/><condition attribute=\"actualend\" operator=\"last-x-days\" value=\"30\"/><condition attribute=\"actualstart\" operator=\"last-x-days\" value=\"30\"/></filter></entity></fetch></ReportEntity></ReportFilter>";
            rsviewer.CRM_filterText = @"Campaign Activities:
                                            Owner: Equals Current User 
                                            Actual End: Last X Days 30
                                            Actual Start: Last X Days 30";

            yield return (rsviewer);

            int Idx = rsviewer.lastResponse.BodyString.IndexOf(idxMarker);
            string match = rsviewer.lastResponse.BodyString.Substring(Idx + 13);
            string redirect = match.Substring(0, match.IndexOf('"'));
            redirect = redirect.Replace("&amp;", "&");

            Reserved_ReportViewerWebControl_axd reportViewer = new Reserved_ReportViewerWebControl_axd(crmServer);
            reportViewer.Url = reportViewer.Url + redirect;
            yield return (reportViewer);

            Idx = reportViewer.lastResponse.BodyString.IndexOf(idxMarker2);
            string match2 = reportViewer.lastResponse.BodyString.Substring(Idx + 12);
            string redirect2 = match2.Substring(0, match2.IndexOf('"'));
            redirect2 = redirect2.Replace("&amp;", "&");

            reportViewer = new Reserved_ReportViewerWebControl_axd(crmServer);
            reportViewer.Url = reportViewer.Url + redirect2;
            yield return (reportViewer);

			this.EndTransaction("CampaignActivityStatusReport");
		}

        private string idxMarker = "<iframe src=\"/Reserved.ReportViewerWebControl.axd?";
        private string idxMarker2 = "<frame src=\"/Reserved.ReportViewerWebControl.axd?";
		private CRMEntity user;
        private CRMEntity report;
        private string crmServer;

        WRPCInfo rpcInfo;
        WebTestRequestHeader headerItem;
        private string tokenKey;
	}
}



